package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.service.DubboCartService;
import com.jt.thread.UserThreadLocal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {

    @Reference(check = false, timeout = 3000)
    private DubboCartService dubboCartService;

    @RequestMapping("/show")
    public String show(Model model) {

        Long userId = UserThreadLocal.get().getId();
        List<Cart> list = dubboCartService.findObject(userId);

        model.addAttribute("cartList", list);
        return "cart";
    }

    /**
     * 业务:完成购物车数量的更新操作
     */
    @RequestMapping("/update/num/{itemId}/{num}")
    @ResponseBody   //ajax结束的标识符
    public void updateCartNum(Cart cart) { //如果{name} 与属性的名称一致,则可以自动的赋值

        Long userId = UserThreadLocal.get().getId();
        cart.setUserId(userId);
        dubboCartService.updateCartNum(cart);
    }

    /**
     * http://www.jt.com/cart/delete/562379.html
     */
    @RequestMapping("/delete/{itemId}")
    public String delete(Cart cart) {
        Long userId = UserThreadLocal.get().getId();
        cart.setUserId(userId);
        dubboCartService.deleteCart(cart);

        return "redirect:/cart/show.html";
    }

    /**
     * 完成购物车入库操作
     * url : http://www.jt.com/cart/add/1474391969.html
     */
    @RequestMapping("/add/{itemId}")
    public String addCart(Cart cart) {

        Long userId = UserThreadLocal.get().getId();
        cart.setUserId(userId);
        dubboCartService.addCart(cart);

        return "redirect:/cart/show.html";
    }
}
